<script setup>
import {ref, watch} from 'vue';

const props = defineProps({
  // 绑定值
  modelValue: {
    type: [String, Number, Boolean],
    default: '',
  },
  // 后置图标
  suffixIcon: {
    type: String,
    default: 'arrow-right',
  },
  // 后置图片
  suffixImg: {
    type: String,
  },
  // 隐藏后置插槽
  hideSuffixSlot: Boolean,
  // 输入框为空时的占位符
  placeholder: String,
  // 格式化显示内容
  formatter: Function,
  // 只读
  readonly: {
    type: Boolean,
    default: true,
  },
  // 自定义样式
  customStyle: Object,
  // 禁用
  disabled: Boolean,
});

const inputValue = ref(undefined);
const emits = defineEmits(['update:modelValue', 'click']);

watch(() => props.modelValue, () => {
  if (props.formatter) {
    inputValue.value = props.formatter(props.modelValue);
    return;
  }
  inputValue.value = props.modelValue;
}, {
  immediate: true,
});

watch(() => inputValue.value, (value) => {
  if (props.formatter || props.readonly) return;
  emits('update:modelValue', value);
});

function handleClick() {
  if (props.disabled) return;
  emits('click');
}
</script>

<template>
  <view
    class="custom-icon-input"
    :class="{disabled: disabled}"
    @click="handleClick">
    <up-input
      v-model="inputValue"
      :readonly="readonly"
      :placeholder="placeholder"
      :customStyle="customStyle"
      :disabled="disabled"
      disabled-color="transparent"
      v-bind="$attrs">
      <template #suffix>
        <slot v-if="!hideSuffixSlot" name="suffix"></slot>
        <up-icon v-if="suffixIcon" :name="suffixIcon" size="24rpx" color="#999"></up-icon>
        <view v-if="suffixImg" class="flex-center u-flex-center">
          <image
            style="width: 44.0rpx; height: 44.0rpx"
            :src="suffixImg">
          </image>
        </view>
      </template>
    </up-input>
  </view>
</template>

<style scoped lang="scss">
.custom-icon-input {
  width: 100%;
}
</style>
